package com.dmw.month_lx.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.dmw.month_lx.dao.PayBillDao;
import com.dmw.month_lx.entity.Organization;
import com.dmw.month_lx.entity.PayBill;
import com.dmw.month_lx.entity.User;
import com.dmw.month_lx.service.PayBillService;

@Service
public class PayBillServiceImpl implements PayBillService {

	@Autowired
	private PayBillDao payBillDao;

	@Override
	@Transactional
	public void insertPayBill(PayBill bill) {
		// 添加主表
		payBillDao.insertPayBill(bill);
		// 获取实体类中封装的对象
		List<User> user = bill.getUsers().stream().filter(item -> item.getName() != null).collect(Collectors.toList());
		if (!user.isEmpty()) {
			for (User us : user) {
				// 通过name查询发薪人员
				User u = payBillDao.selectUserByName(us.getName());
				if (u != null) {
					// 直接添加中间表
					payBillDao.insertBillUser(bill.getId(), u.getId());
				} else {
					// 添加发薪人员表
					payBillDao.insertUser(us);
					// 添加中间表
					payBillDao.insertBillUser(bill.getId(), us.getId());
				}
			}
		}
	}

	@Override
	public List<Organization> selectOrganization(Organization organ) {
		// TODO Auto-generated method stub
		return payBillDao.selectOrganization(organ);
	}

	@Override
	public PageInfo<PayBill> selectPayBill(Integer pageNum, Integer pageSize, PayBill bill) {
		// TODO Auto-generated method stub
		PageHelper.startPage(pageNum, pageSize);
		List<PayBill> list = payBillDao.selectPayBill(bill);
		return new PageInfo<>(list);
	}

	@Override
	public int deletePayBill(Integer id) {
		// TODO Auto-generated method stub
		//再删除从表
		payBillDao.deleteUser(id);
		//最后删除主表
		payBillDao.deletePayBill(id);
		//先删除中间表
		return payBillDao.deleteBillUser(id);
			
	}

	@Override
	public PayBill selectPayBillById(Integer id) {
		// TODO Auto-generated method stub
		return payBillDao.selectPayBillById(id);
	}

	@Override
	@Transactional
	public void updatePayBill(PayBill bill) {
		// TODO Auto-generated method stub
		//删除从表
		payBillDao.deleteUser(bill.getId());
		//删除中间表
		payBillDao.deleteBillUser(bill.getId());
		//修改主表
		payBillDao.updatePayBill(bill);
		//过滤空集合
		List<User> users = bill.getUsers().stream().filter(us->us.getName()!=null).collect(Collectors.toList());
		if(!users.isEmpty()) {
			for (User u : users) {
				//通过名字查询
				User user = payBillDao.selectUserByName(u.getName());
				//判断user是否有值
				if(user!=null) {
					//user不为空的话
					//直接添加中间表
					payBillDao.insertBillUser(bill.getId(), user.getId());
				}else {
					//user为空的话
					//先添加user表
					payBillDao.insertUser(u);
					//再添加中间表
					payBillDao.insertBillUser(bill.getId(), u.getId());
				}
			}
		}
	}

	

}
